<template>
  <div>
    <r-search
      :searchForm="searchForm"
      :searchHandle="searchHandle"
      :searchData="searchData"
    />
    <r-search :searchHandle="searchHandleAdd" />
    <r-table
      :isSelection="false"
      :isIndex="false"
      :isPagination="true"
      :tableData="tableData"
      :tableCols="tableCols"
      :tablePage="tablePage"
      @refresh="init()"
    ></r-table>

    <r-form
      labelWidth="150px"
      :isHandle="true"
      :formRules="formRules"
      :formCols="formCols"
      :formHandle="formHandle"
      :formData="formData"
      ref="elForm"
      :inline="false"
      dialogWidth="850px"
    >
      <!--            <div :slot="'door'+(index+1)" v-for="(item,index) in callLists" :key="index">-->
      <!--                <span v-for="(item2,index2) in item" :key="index2" style="margin-right:10px;margin-bottom:10px;float:left;cursor: pointer;">-->
      <!--                    <el-tag @click="callClick(item2,index)" :type="item2.type">{{index2+1}}号称</el-tag>-->
      <!--                </span>-->
      <!--            </div>-->

      <div slot="slot3">
        <div
          id="searchResultPanel"
          style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"
        ></div>
        <p>
          点击地图拾取坐标 经度：{{ formData.lng }} 纬度：{{ formData.lat }}
        </p>
        <div id="l-map"></div>
      </div>
    </r-form>
    <r-form
      :formRules="formRulesEditPsw"
      :formHandle="formHandleEditPsw"
      :formData="formDataEditPsw"
      :formCols="formColsEditPsw"
      ref="elFormEditPsw"
      labelWidth="200px"
      dialogWidth="1000px"
      :isHandle="true"
    />
    <r-form
      :formRules="formRulesActive"
      :formHandle="formHandleActive"
      :formData="formDataActive"
      :formCols="formColsActive"
      ref="elFormActive"
      labelWidth="200px"
      dialogWidth="1000px"
      :isHandle="true"
    />
    <operatorDetail ref="operatorDetail"></operatorDetail>
  </div>
</template>

<script>
import baidumap from "../js/baidumap";
import { isMobile } from "@/utils/validate";
import { clearLoginInfo } from "@/utils";
import operatorDetail from "./cus/operatorDetail.vue";
export default {
  name: "operator",
  components: { operatorDetail },
  data() {
    var checkpass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("Enter Again PassWord"));
      } else if (value !== this.formDataEditPsw.password) {
        callback(new Error("The password is not the same!"));
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error("Phone格式错误"));
      } else {
        callback();
      }
    };
    return {
      baiduMap: null,
      //
      searchData: {
        name: "",
        phone: "",
        address: "",
        contacts: ""
      },
      searchForm: [
        {
          type: "input",
          prop: "name",
          placeholder: "OperatorName",
          width: 180
        },
        {
          type: "input",
          prop: "address",
          placeholder: "Operator地址",
          width: 180
        },
        {
          type: "input",
          prop: "contacts",
          placeholder: "联系人",
          width: 180
        },
        {
          type: "input",
          prop: "phone",
          placeholder: "Phone",
          width: 180
        }
        // {
        //     type: 'select',
        //     prop: 'state',
        //     placeholder: 'Status',
        //     width: 150,
        //     options: [
        //         {
        //             label: '正常',
        //             value: '1'
        //         },
        //         {
        //             label: 'Forbidden',
        //             value: '2',
        //         },
        //     ]
        // },
      ],
      searchHandleAdd: [
        {
          label: "AddOperator",
          type: "primary",
          plain: true,
          icon: "el-icon-circle-plus-outline",
          handle: e => this.createdAcc()()
        }
      ],
      searchHandle: [
        {
          label: "Search",
          type: "success",
          icon: "el-icon-search",
          plain: true,
          handle: e => this.getData()
        }
        // {
        //     label: 'Reset',
        //     icon: 'el-icon-refresh-right',
        //     handle: e => this.searchFromReset()
        // }
      ],
      tableData: [],
      tableCols: [
        {
          label: "序号",
          prop: "id"
        },
        {
          label: "OperatorName",
          prop: "name"
        },
        {
          label: "登录账号",
          prop: "account"
        },
        {
          label: "Operator地址",
          prop: "address"
        },
        {
          label: "联系人",
          prop: "contacts"
        },
        {
          label: "Phone",
          prop: "phone"
        },
        // {
        //     label: '设备信息',
        //     prop: 'areaNum'
        // },
        {
          label: "运营换电",
          prop: "operateHd",
          theme: e => (e.operateHd == "2" ? "danger" : "primary"),
          type: "tag",
          formatter: e => (e.operateHd == 1 ? "是" : "否")
        },
        // {
        // 	label: '运营充电',
        // 	prop: 'operateCd',
        // 	theme: e => (e.operateCd == '2' ? 'danger' : 'primary'),
        // 	type: 'tag',
        // 	formatter: e => (e.operateCd == 1 ? '是' : '否')
        // },
        // {
        // 	label: '运营租车',
        // 	prop: 'operateZc',
        // 	theme: e => (e.operateZc == '2' ? 'danger' : 'primary'),
        // 	type: 'tag',
        // 	formatter: e => (e.operateZc == 1 ? '是' : '否')
        // },
        // {
        //   label: '站点数量',
        //   prop: 'mchNum'
        // },
        {
          label: "Update Time",
          prop: "createdTime"
        },
        {
          label: "EnableStatus",
          prop: "state",
          theme: e => (e.state == "2" ? "danger" : "primary"),
          type: "tag",
          formatter: e => (e.state == 1 ? "Enable" : "Forbidden")
        },
        {
          label: "Operations",
          type: "button",
          width: 400,

          btnList: [
            {
              label: "View Details",
              type: "success",
              plain: true,
              // isShow: e => e.orderId == '123' ? true : false,
              handle: row => {
                this.$refs.operatorDetail.init(row.id);
              }
            },
            {
              label: "Edit",
              type: "primary",
              plain: true,
              // isShow: e => e.orderId == '123' ? true : false,
              handle: row => this.createdAcc(row)
            },
            {
              label: "Delete",
              type: "danger",
              plain: true,
              // isShow: e => e.orderId == '123' ? true : false,
              handle: row => this.delRow(row)
            },
            {
              label: "进入后台",
              type: "warning",
              plain: true,
              handle: row => {
                this.$confirm(`确定退出Current账号?`, "Hint", {
                  confirmButtonText: "Confirm",
                  cancelButtonText: "Cancel",
                  type: "warning"
                })
                  .then(() => {
                    // console.warn('main-navbar.vue重新加入代码')
                    // this.$http.get("/sysUser/sys/exitlogin").then(res => {
                    //   if (res.code === 200) {
                    //     clearLoginInfo()
                    //     this.$router.push({ name: 'login' })
                    //   }
                    // })

                    sessionStorage.role = "";
                    clearLoginInfo();
                    sessionStorage.mainTabs_text = "";
                    this.$store.commit("common/updateMainTabs", []);
                    this.$router.push({
                      path: "/login"
                    });
                  })
                  .catch(() => {});
              }
            }
          ]
        }
      ],
      tablePage: { limit: 10, page: 1, total: 0 },
      formData: {
        name: "",
        phone: "",
        account: "",
        password: "",
        contacts: "",
        operateHd: false,
        // operateCd: false,
        // operateZc: false,
        address: "",
        lng: "",
        lat: ""
      },
      formCols: [
        {
          type: "input",
          label: "OperatorName",
          placeholder: "Please InputOperatorName",
          width: 350,
          prop: "name"
        },
        {
          type: "input",
          label: "联系电话",
          placeholder: "Please Enter",
          width: 200,
          prop: "phone"
        },
        {
          type: "input",
          label: "联系人",
          placeholder: "Please Enter",
          width: 350,
          prop: "contacts"
        },
        {
          type: "input",
          label: " 登录账号",
          placeholder: "Please Input登录账号",
          width: 350,
          prop: "account",
          isShow: row => this.formColsIsShow(row)
        },
        {
          type: "input",
          label: " 密码",
          placeholder: "Please Input密码",
          width: 350,
          prop: "password",
          isShow: row => this.formColsIsShow(row)
        },
        {
          type: "switch",
          label: "是否运营换电",
          placeholder: "Please Enter",
          width: 200,
          prop: "operateHd"
        },
        // { type: 'switch', label: '是否运营充电', placeholder: 'Please Enter', width: 200, prop: 'operateCd' },
        // { type: 'switch', label: '是否运营租车', placeholder: 'Please Enter', width: 200, prop: 'operateZc' },
        {
          type: "input",
          id: "suggestId",
          label: "详细地址",
          width: 350,
          prop: "address"
        },
        { type: "slot", name: "slot3", label: "", prop: "lng" }
      ],
      formRules: {
        name: [{ required: true, message: "OperatorName", trigger: "blur" }],
        phone: [
          { required: true, message: "联系方式", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ],
        contacts: [{ required: true, message: "联系人", trigger: "blur" }],
        account: [{ required: true, message: "登录账号", trigger: "blur" }],
        password: [{ required: true, message: "密码", trigger: "blur" }],
        address: [
          { required: true, message: "请填写详细地址", trigger: "blur" }
        ],
        lng: [
          { required: true, message: "请点击地图选择经纬度", trigger: "blur" }
        ]
      },
      formHandle: [
        {
          label: "Cancel",
          handle: e => this.elFormVisible()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmit()
        }
      ],
      formDataEditPsw: {
        password: "",
        enterPassword: ""
      },
      formColsEditPsw: [
        {
          type: "input",
          label: " 密码",
          placeholder: "Please Input密码",
          width: 350,
          prop: "password"
        },
        {
          type: "input",
          label: "确认密码",
          placeholder: "Please Input确认密码",
          width: 350,
          prop: "enterPassword"
        }
      ],
      formRulesEditPsw: {
        password: [{ required: true, message: "密码", trigger: "blur" }],
        enterPassword: [
          {
            required: true,
            validator: checkpass2,
            message: "请确认两次密码是否一致",
            trigger: "blur"
          }
        ]
      },
      formHandleEditPsw: [
        {
          label: "Cancel",
          handle: e => this.elFormVisibleEditPsw()
        },
        {
          label: "Confirm",
          type: "success",
          handle: e => this.elFormSubmitEditPsw()
        }
      ],
      //Forbidden恢复
      formDataActive: {
        isActive: ""
      },
      formRulesActive: {},
      formColsActive: [
        { label: "是否恢复选定账号", width: 350, prop: "isActive" }
        // { type: "input", label: "确认密码", placeholder: 'Please Input确认密码', width: 350, prop: "enterPassword" },
      ],
      formHandleActive: [
        {
          label: "Cancel",
          handle: e => this.elFormVisibleActive()
        },
        {
          label: "Confirm",
          type: "primary",
          handle: e => this.elFormSubmitActive()
        }
      ],
      checkBox: [],

      callLists: [[], []]
    };
  },
  created() {},
  mounted() {
    this.setCall(20, 2);
    this.getData();
  },
  methods: {
    delRow(row) {
      this.$confirm("确定要Delete吗？", "Hint", {
        confirmButtonText: "Confirm",
        cancelButtonText: "Cancel",
        type: "warning"
      })
        .then(async () => {
          var res = await this.apis.operator_del({
            id: row.id
          });

          this.$message({
            type: "success",
            message: "DeleteSuccess!"
          });
          this.getData();
        })
        .catch(() => {});
    },
    formColsIsShow() {
      if (this.formData.id) {
        this.formRules.password[0].required = false;
        return true;
      } else {
        this.formRules.password[0].required = true;
        return true;
      }
    },
    setCall(callNum, doorNum) {
      var arr = [];
      for (var i = 0; i < doorNum; i++) {
        var arr2 = [];
        for (var j = 0; j < callNum; j++) {
          arr2.push({
            type: "info",
            status: 1,
            id: j + 1
          });
        }
        arr.push(arr2);
      }

      this.callLists = arr;
    },
    callClick(item, index) {
      console.log(item);
      console.log(index);
      for (var i = 0; i < this.callLists.length; i++) {}
      item.type = "success";
    },
    map(row) {
      var that = this;
      var map = baidumap(that);
      this.baiduMap = map;
      var geoc = new BMap.Geocoder();
      map.addEventListener("click", function(e) {
        that.formData.lng = e.point.lng;
        that.formData.lat = e.point.lat;

        var pt = e.point;
        geoc.getLocation(pt, function(rs) {
          var addComp = rs.addressComponents;
          that.formData.city = addComp.city;
          // alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
        });
      });
      map.enableScrollWheelZoom(); //Enable滚轮放大缩小，默认Forbidden
      map.enableContinuousZoom(); //Enable地图惯性拖拽，默认Forbidden
    },
    createdAcc(row) {
      if (row) {
        this.formData.id = row.id;
      }

      this.elFormVisible().then(res => {
        this.map();

        if (row) {
          Object.keys(this.formData).forEach(key => {
            if (
              key == "operateHd" ||
              key == "operateCd" ||
              key == "operateZc"
            ) {
              row[key] = row[key] == 1 ? true : false;
            }
            this.formData[key] = row[key];
          });
          this.formData.id = row.id;
        }
      });
    },
    elFormSubmit() {
      this.$refs.elForm.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.submit();
        }
      });
    },
    async submit() {
      if (this.formData.id) {
        var res = await this.apis.operator_updata({
          name: this.formData.name,
          phone: this.formData.phone,
          account: this.formData.account,
          password: this.formData.password,
          address: this.formData.address,
          lng: this.formData.lng,
          lat: this.formData.lat,
          operateHd: this.formData.operateHd ? 1 : 2,
          operateCd: this.formData.operateCd ? 1 : 2,
          operateZc: this.formData.operateZc ? 1 : 2,
          contacts: this.formData.contacts,
          id: this.formData.id
        });
      } else {
        var res = await this.apis.operator_save({
          name: this.formData.name,
          phone: this.formData.phone,
          account: this.formData.account,
          password: this.formData.password,
          address: this.formData.address,
          lng: this.formData.lng,
          lat: this.formData.lat,
          operateHd: this.formData.operateHd ? 1 : 2,
          operateCd: this.formData.operateCd ? 1 : 2,
          operateZc: this.formData.operateZc ? 1 : 2,
          contacts: this.formData.contacts
        });
      }

      this.elFormVisible();

      this.getData();

      this.$message({
        message: "Operations Success",
        type: "success"
      });
    },
    async getData() {
      var res = await this.apis.operator_list({
        name: this.searchData.name,
        phone: this.searchData.phone,
        contacts: this.searchData.contacts,
        address: this.searchData.address,

        pageNum: this.tablePage.page,
        pageSize: this.tablePage.limit
      });
      console.log(res);
      var list = res.rows || [];
      this.tableData = list;
      this.tablePage.total = res.total;
    },
    elFormDetail(row) {
      // this.elFormVisible()
    },
    elFormDetailEditPsw(row) {
      Object.keys(this.formDataEditPsw).forEach(key => {
        this.formDataEditPsw[key] = row[key];
      });
      this.formDataEditPsw.id = row.id;
      this.elFormVisibleEditPsw();
    },
    elFormVisibleEditPsw(tit) {
      if (this.$refs.elFormEditPsw.$refs.ruleFormEditPsw) {
        this.$refs.elFormEditPsw.$refs.ruleFormEditPsw.resetFields();
        this.$data.formDataEditPsw = this.$options.data.call(
          this
        ).formDataEditPsw;
      }
      this.$refs.elFormEditPsw.dialogFormVisible = !this.$refs.elFormEditPsw
        .dialogFormVisible;
      this.$refs.elFormEditPsw.dialogFormTitle = tit
        ? tit
        : this.formDataEditPsw.id
        ? "Edit"
        : "Add";

      if (this.$refs.elFormEditPsw.dialogFormVisible) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        });
      }
    },
    init() {
      this.getData();
    },
    async elFormSubmitEditPsw() {
      let res = await this.api.opedit(this.formDataEditPsw);
      if (res) {
        // this.init()
        this.elFormVisibleEditPsw();
      }
    },
    elFormDetailActive(row) {
      Object.keys(this.formDataActive).forEach(key => {
        this.formDataActive[key] = row[key];
      });
      this.formDataActive.id = row.id;
      this.elFormVisibleActive();
    },
    elFormVisibleActive(tit) {
      if (this.$refs.elFormActive.$refs.ruleFormActive) {
        this.$refs.elFormActive.$refs.ruleFormActive.resetFields();
        this.$data.formDataActive = this.$options.data.call(
          this
        ).formDataActive;
      }
      this.$refs.elFormActive.dialogFormVisible = !this.$refs.elFormActive
        .dialogFormVisible;
      this.$refs.elFormActive.dialogFormTitle = tit
        ? tit
        : this.formDataActive.id
        ? "Edit"
        : "Add";

      if (this.$refs.elFormActive.dialogFormVisible) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            resolve();
          }, 2000);
        });
      }
    },
    async elFormSubmitActive() {
      // console.log(this.formDataActive.id);
      let res = await this.api.opchange(this.formDataActive);
      if (res) {
        this.getData();
        this.elFormVisibleActive();
      }
    }
  }
};
</script>

<style scoped lang="scss">
#l-map {
  height: 250px;
  width: 100%;
}

#r-result {
  width: 100%;
}
</style>
